package Concurrency.AsynTaskExecute;

/**
 * 使用ExecutorService编写并发异步执行任务类似于写顺序程序一样，不用关心程序的创建和协调，只需要提交任务、处理结果即可。
 */

import sun.nio.ch.ThreadPool;

import java.util.Random;
import java.util.concurrent.*;

public class BasicDemo {
    static class Task implements Callable<Integer> {

        @Override
        public Integer call() throws Exception {
           int sleepSeconds = new Random().nextInt(1000);
           Thread.sleep(sleepSeconds);
           return sleepSeconds;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        // 用工厂类Executors创建了一个任务执行服务
        //ExecutorService executor = Executors.newSingleThreadExecutor();
        // 使用自己定义的简单执行服务SimpleExecutorService来提交任务，并获取结果
        SimpleExecutorService executor = new SimpleExecutorService();
        Future<Integer> future = executor.submit(new Task());
        System.out.println(executor.isShutdown());
        //模拟执行其他任务
        Thread.sleep(100);
        try {
            System.out.println(future.get());
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        // 调用shutdown方法，关闭 <任务执行服务>
        executor.shutdown();
        System.out.println(executor.isShutdown());
    }
}
